#!/bin/bash
export PATH=$TONE_BM_RUN_DIR/bin:$PATH
[[ -n $NUMACTL ]] || NUMACTL='numactl -C 0 -m 0'

setup()
{
    [ -n "$SERVER" ] && server=${SERVER%% *} || server=127.0.0.1
    echo "Run netserver on host: $server"

    if [ $server = 127.0.0.1 ]; then
        source "$TONE_BM_SUITE_DIR"/sockperf-server.sh
    else
        ssh $server "NUMACTL='$NUMACTL' TONE_ROOT=$TONE_ROOT TONE_BM_RUN_DIR=$TONE_BM_RUN_DIR server=$server $TONE_BM_SUITE_DIR/sockperf-server.sh" &
        pid=$(ps aux | grep "ssh $server" | awk '{print $2}' | sort -n | head -n 1)
        sleep 3 && kill "${pid}" && echo "ssh command is complete"
    fi
}

run()
{
    sleep 1
    [ -n "$runtime" ] || runtime=180
    msg_size=${msg_size%%[bB]}
    if [ -z "$msg_size" ]; then
        client_cmd="$NUMACTL sockperf $test -i $server --time $runtime"
    else
        client_cmd="$NUMACTL sockperf $test -i $server --time $runtime --msg-size $msg_size"
    fi

    if [ $server = 127.0.0.1 ]; then
        client_cmd="$client_cmd --sender-affinity 0 --receiver-affinity 1"
    else
        client_cmd="$client_cmd --sender-affinity 1 --receiver-affinity 1"
    fi

    if [ "$protocol" == udp ]; then
        echo "sockperf: UDP"
        logger $client_cmd
    else
        echo "sockperf: TCP"
        logger $client_cmd --tcp
    fi
}

teardown()
{
    if [ $server = 127.0.0.1 ];then
        pkill -f "sockperf server" &>/dev/null || true
    else
        ssh $server "pkill -f 'sockperf server'" || true
    fi
}

parse()
{
    "$TONE_BM_SUITE_DIR"/parse.awk
}

